const axios = require('axios');
const fs = require('fs').promises;
const path = require('path');

class TokenService {
    constructor() {
        this.tokenFilePath = path.join(__dirname, '../../.token-cache.json');
    }

    async loadTokenFromCache() {
        try {
            const data = await fs.readFile(this.tokenFilePath, 'utf8');
            const cache = JSON.parse(data);
            
            // Check if token is expired (considering a 1-day safety margin)
            if (cache.expireTime && Date.now() < cache.expireTime - 24 * 60 * 60 * 1000) {
                return cache.token;
            }
        } catch (error) {
            // File doesn't exist or is invalid, which is fine
            return null;
        }
        return null;
    }

    async saveTokenToCache(token, expireTime) {
        try {
            await fs.writeFile(
                this.tokenFilePath,
                JSON.stringify({
                    token,
                    expireTime,
                    updatedAt: Date.now()
                })
            );
        } catch (error) {
            console.error('Error saving token to cache:', error);
            // Non-blocking error, we can continue even if save fails
        }
    }

    async getAccessToken() {
        // Try to get token from cache first
        const cachedToken = await this.loadTokenFromCache();
        if (cachedToken) {
            return cachedToken;
        }

        try {
            const response = await axios({
                method: 'POST',
                url: `${process.env.BAIDU_API_URL}/oauth/2.0/token`,
                params: {
                    grant_type: 'client_credentials',
                    client_id: process.env.BAIDU_API_KEY,
                    client_secret: process.env.BAIDU_SECRET_KEY
                }
            });

            const token = response.data.access_token;
            // Set token expiration time (30 days in milliseconds)
            const expireTime = Date.now() + (30 * 24 * 60 * 60 * 1000);
            
            // Save token to cache
            await this.saveTokenToCache(token, expireTime);
            
            return token;
        } catch (error) {
            console.error('Error getting access token:', error);
            throw new Error('Failed to get access token');
        }
    }
}

module.exports = new TokenService(); 